package com.quick.develop.flowable.framework.cmd;

import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cmd.NeedsActiveTaskCmd;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.HistoricTaskService;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.Optional;

/**
 * desc: 标记任务处理方式
 *
 * @author junyuan.liu
 * @date 2023/6/16 11:39
 */
public class SetTaskScopeTypeCmd extends NeedsActiveTaskCmd<Void> {
    private static final long serialVersionUID = -8605669793563408864L;

    protected String executeCmd;

    public SetTaskScopeTypeCmd(String taskId, String executeCmd) {
        super(taskId);
        this.executeCmd = executeCmd;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        HistoricTaskService historicTaskService = CommandContextUtil.getHistoricTaskService(commandContext);
        TaskService taskService = CommandContextUtil.getTaskService(commandContext);
        HistoricTaskInstanceEntity historicTask = historicTaskService.getHistoricTask(taskId);

        Optional.ofNullable(executeCmd).ifPresent(cmd -> {
            taskEntity.setScopeType(cmd);
            historicTask.setScopeType(cmd);
            taskService.updateTask(taskEntity, false);
            historicTaskService.updateHistoricTask(historicTask, false);
        });
        
        return null;
    }
}
